<?php
/*
 * 公共函数
 * Created by PhpStorm.
 * User: zhangChao
 * Date: 2018/10/22
 * Time: 15:24
 */
use think\Db;

/**
 * @param $status  获取成功传递1 失败传递0
 * @param $message 返回信息
 * @param array $data 返回数据
 * @param int $httpCode 正常200 错误请求400 服务器内部错误500
 * @return \think\response\Json
 */
function show($status, $message, $data=[], $httpCode=200) {
    $data = [
        'code' => $status,
        'msg' => $message,
        'message' => $message,
        'data' => $data,
    ];
    return json($data,$httpCode);
}

/**
 * 自定义日志记录
 */
function myLog($var,$tag="debug",$level="INFO"){
    $record = 1;
    $level = strtolower($level);
    // if($level=="info") $record = 0;
    if($record){
        if(is_array($var) || is_object($var)) $msg = json_encode($var,JSON_UNESCAPED_UNICODE);
        else $msg = $var;
        $date = date("Ymd");

        $fp = fopen(LOG_PATH.$level."_mylog_".$date.".log","a+");

        fputs($fp,date("Y-m-d H:i:s")."##".$tag."::".$level."\n");
        fputs($fp,$msg."\n\n###################\n\n");
        fclose($fp);
    } 
    
}


function uncamelizeRs($rs,$separator="_"){
    if(is_object($rs)) {
        $list = $rs->toArray();
    }
    else $list = $rs;
    // if($rs) {
    //     $rs = collection($rs)->toArray();
    // }
    foreach($list as $i=>$row) {
        if(is_array($row) || is_object($row)){
            
            unset($list[$i]);
            $i = uncamelize($i);
            $list[$i] = uncamelizeRs($row);
        }
        else{
            unset($list[$i]);
            $i = uncamelize($i);
            $list[$i] = $row;
        }
    }

    return $rs;
}

function camelizeArr($arr,$separator="_"){
    
    foreach($arr as $key=>$value){
        unset($arr[$key]);
        $key = camelize($key,$separator);
        $arr[$key] = $value;
    }

    return $arr;
}

function uncamelizeArr($arr,$separator="_"){
    
    foreach($arr as $key=>$value){
        unset($arr[$key]);
        $key = uncamelize($key,$separator);
        $arr[$key] = $value;
    }

    return $arr;
}

/**
 * 下划线转驼峰
 * 思路:
 * step1.原字符串转小写,原字符串中的分隔符用空格替换,在字符串开头加上分隔符
 * step2.将字符串中每个单词的首字母转换为大写,再去空格,去字符串首部附加的分隔符.
 */
function camelize($uncamelized_words,$separator='_')
{
    $uncamelized_words = $separator. str_replace($separator, " ", strtolower($uncamelized_words));
    return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator );
}

/**
 * 驼峰命名转下划线命名
 * 思路:
 * 小写和大写紧挨一起的地方,加上分隔符,然后全部转小写
 */
function uncamelize($camelCaps,$separator='_')
{
    return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
}
